package com.augmentum.oes.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.augmentum.oes.util.JDBCUtil;

@Repository
public class BaseDao {
    @Autowired
    protected JdbcTemplate jdbcTemplate;

    @Autowired
    protected SqlSessionTemplate sst;

    // ADD
    public <T> int saveAll(T t) {
        Map<String, Object> map = JDBCUtil.toMap(t);
        final Set<Entry<String, Object>> entry = map.entrySet();
        String tableName = JDBCUtil.getTable(t);
        StringBuffer sb = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        sb.append("INSERT INTO " + tableName + "(");

        for (Entry<String, Object> en : entry) {
            sb.append(en.getKey() + ",");
            sb2.append("?,");
        }
        sb.append("create_time) VALUES (");
        sb2.append("now())");
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final String sql = sb.toString() + sb2.toString();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
                int i = 1;
                for (Entry<String, Object> en : entry) {
                    ps.setObject(i, en.getValue());
                    i++;
                    }
                return ps;
            }
            
        }, keyHolder);
        return keyHolder.getKey().intValue();
    }

    public <T> void save(String sql, T t) {
        final Map<String, Object> map = JDBCUtil.toMap(t);
        final String[] sqlSplit = sql.substring(sql.indexOf("(", 0) + 1, sql.indexOf(")", 0)).split(",");
        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                for (int i = 0; i < sqlSplit.length; i++) { 
                    ps.setObject(i + 1, map.get(sqlSplit[i].trim()));
                }
            }
        });
    }
    // DELETE UPDATE
    /*
     * public int common(String sql, Object... obj) { Connection conn =
     * (Connection) AppContext.getInstance().getData("CONNECTION");
     * PreparedStatement ps = null; int flag = 0; try { ps =
     * conn.prepareStatement(sql); if (obj != null && obj.length > 0) { for (int
     * i = 0; i < obj.length; i++) { ps.setObject(i + 1, obj[i]); } } flag =
     * ps.executeUpdate(); } catch (SQLException e) { throw new
     * DBException(MessageUtils.DB_ACCESS_ERROR,
     * MessageUtils.buildMessage(MessageUtils.DB_ACCESS_ERROR)); } finally {
     * JDBCUtil.close(null, ps, null); } return flag; }
     */
    /*
     * public int count(String sql, Object... obj) { Connection conn =
     * (Connection) AppContext.getInstance().getData("CONNECTION");
     * PreparedStatement ps = null; ResultSet rs = null; int count = 0; try { ps
     * = conn.prepareStatement(sql); if (obj != null && obj.length > 0) { for
     * (int i = 0; i < obj.length; i++) { ps.setObject(i + 1, obj[i]); } } rs =
     * ps.executeQuery(); while (rs.next()) { count = rs.getInt(1); } } catch
     * (SQLException e) { throw new DBException(MessageUtils.DB_ACCESS_ERROR,
     * MessageUtils.buildMessage(MessageUtils.DB_ACCESS_ERROR)); } finally {
     * JDBCUtil.close(rs, ps, null); } return count; }
     * 
     * // QUERY public <T> List<T> query(Class<T> clazz, String sql, Object...
     * obj) { Connection conn = (Connection)
     * AppContext.getInstance().getData("CONNECTION"); T t = null;
     * PreparedStatement ps = null; ResultSet rs = null; try { List<T> list =
     * new ArrayList<T>(); ps = conn.prepareStatement(sql); if (obj != null &&
     * obj.length > 0) { for (int i = 0; i < obj.length; i++) { ps.setObject(i +
     * 1, obj[i]); } } rs = ps.executeQuery(); while (rs.next()) { t =
     * clazz.newInstance(); JDBCUtil.toBean(t, rs); list.add(t); } return list;
     * } catch (Exception e) { throw new
     * DBException(MessageUtils.DB_ACCESS_ERROR, e.getMessage()); } finally {
     * JDBCUtil.close(rs, ps, null); } }
     * 
     * public <T> List<T> queryAll(Class<T> clazz) { String tableName =
     * clazz.getAnnotation(Table.class).value(); String sql = "SELECT * FROM " +
     * tableName; return query(clazz, sql); }
     */
}
